(function () {
    var core = ecui,
        util = core.util,
        dom = ecui.dom,
        ticketItems,
        ticketItem,
        playId;

    // 更新已验收、待验收票的数量
    function refreshCheckTicket() {
        ecui.esr.request(
            'acount@GET /erp-management/play/h5/start-check-ticket/${id}',
            function () {
                var acount = ecui.esr.getData('acount');
                ecui.$('checkticketentryamount').innerHTML = acount.entryAmount;
                ecui.$('checkticketlastamount').innerHTML = acount.lastAmount;
            }
        );
    }
    ecui.util.extend(NS.ui, {
        // 扫描二维码tab
        Tab: ecui.inherits(
            ecui.ui.Tab,
            {
                // 点击扫描二维码
                ontitleclick: function (event) {
                    if (event.index === 1) {
                        // this.setSelected(0);
                        wx.scanQRCode({
                            needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                            scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
                            success: function (res) {
                                var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                                // 请求www.showstart.com资源时，跨域报错
                                ecui.io.ajax(result.replace('www.showstart.com', 'wap.showstart.com'), {
                                    onsuccess: function (text) {
                                        var mobiles = text.match(/<li>.+(1\d{10})<\/li>/);
                                        this.getItem(1).getContainer().innerHTML += mobiles[1];
                                        ecui.get('ticket-check-mobile').setValue(mobiles[1]);
                                        ecui.dispatchEvent(ecui.get('ticket-check'), 'click');
                                    }.bind(this),
                                    onerror: function (err) {
                                        ecui.tip('warn', JSON.stringify(err));
                                    }.bind(this)
                                });
                            }.bind(this)
                        });
                    }
                    event.exit();
                    return false;
                }
            }
        ),
        // 验票按钮 模糊查询所有票务信息
        Check: ecui.inherits(
            mao.ui.Submit,
            {
                onclick: function () {
                    var mobile = ecui.get('ticket-check-mobile');
                    if (!mobile) {
                        return;
                    }
                    mobile = mobile.getValue();
                    if (!mobile) {
                        ecui.tip('warn', '请输入手机尾号');
                        return;
                    }
                    this.request(
                        'data@GET /erp-management/play/h5/check-ticket/' + playId + '?mobile=' + mobile,
                        function () {
                            var data = ecui.esr.getData('data');
                            if (data instanceof Object) {
                                ticketItems = data;

                                ticketItems.forEach(function (item) {
                                    item.tickets = {};
                                    item.ticketInfoData.forEach(function (item1) {
                                        if (!item.tickets[item1.ticketType]) {
                                            item.tickets[item1.ticketType] = {
                                                channelName: item1.channelName,
                                                entryNum: 0,
                                                all: 0,
                                                items: []
                                            };
                                        }
                                        if (item1.entryStatus) {
                                            item.tickets[item1.ticketType].entryNum += 1;
                                        }
                                        item.tickets[item1.ticketType].all += 1;
                                        item.tickets[item1.ticketType].items.push(item1);
                                    });
                                });

                                if (data.length === 1) {
                                    if (data[0].total < 1) {
                                        ecui.tip('warn', '该手机号未没有相关票务信息');
                                        return;
                                    }
                                    ticketItem = data[0];
                                    util.timer(function () {
                                        var panel = ecui.get('check-ticket-mobile-panel');
                                        ecui.dispatchEvent(dom.first(dom.first(panel.getBody())).getControl(), 'click');
                                    }, 0);
                                } else if (data.length < 1) {
                                    ecui.tip('warn', '未搜索到订单');
                                    return;
                                }
                                var acount = ecui.esr.getData('acount');
                                var dialog = mao.initDialog(ecui.$('dialogContainer'), 'checkTicketDialog', { ticketItems: data, 'entryAmount': acount.entryAmount, 'lastAmount': acount.lastAmount });
                                dialog.showModal();
                                ecui.setFocused(dialog);
                                console.log(ticketItems);
                            }
                        }
                    );
                }
            }
        ),
        // 模糊查询 票务信息 列表弹窗
        CheckTicketDialog: ecui.inherits(
            ecui.ui.Dialog,
            {
                onblur: function () {
                    this.hide();
                }
            }
        ),
        // 批量验票 按钮
        CheckTicket: ecui.inherits(
            mao.ui.Submit,
            {
                onclick: function () {
                    var children = dom.children(ecui.get('check-ticket-panel').getBody()),
                        req = false,
                        ticketIds = [],
                        inputContainer = dom.last(document.forms.admissionTicketForm);

                    inputContainer.innerHTML = '';
                    children.forEach(function (item, index) {
                        var control = item.getControl(),
                            index1 = control.getValue();
                        if (control.isChecked()) {
                            var num = +dom.last(dom.last(item)).getControl()._uNumber.getValue();
                            if (num > 0) {
                                ticketItem.tickets[index1].items.forEach(function (item1) {
                                    if (num && !item1.entryStatus) {
                                        req = true;
                                        ticketIds.push(item1.id);
                                        num--;
                                    }
                                });
                            }
                        }
                    });

                    ticketIds.forEach(function (item) {
                        dom.insertHTML(inputContainer, 'BEFOREEND', '<input type="text" value="' + item + '" name="playTicketDetailIds">');
                    });
                    if (req) {
                        this.request(
                            'data@FORM /erp-management/play/h5/admission?admissionTicketForm',
                            function () {
                                var data = ecui.esr.getData('data');
                                if (data instanceof Object) {
                                    this.findControl(ecui.ui.Dialog).hide();
                                    refreshCheckTicket();
                                    ecui.tip('warn', '成功入场');
                                }
                            }
                        );
                    }
                }
            }
        ),
        // 全部验票 按钮
        CheckTicketAll: ecui.inherits(
            mao.ui.Submit,
            {
                onclick: function () {
                    var inputContainer = dom.last(document.forms.admissionTicketForm),
                        req = false;

                    inputContainer.innerHTML = '';
                    for (var key in ticketItem.tickets) {
                        if (ticketItem.tickets.hasOwnProperty(key)) {
                            ticketItem.tickets[key].items.forEach(function (item) {
                                if (!item.entryStatus) {
                                    req = true;
                                    dom.insertHTML(inputContainer, 'BEFOREEND', '<input type="text" value="' + item.id + '" name="playTicketDetailIds">');
                                }
                            });
                        }
                    }
                    if (req) {
                        this.request(
                            'data@FORM /erp-management/play/h5/admission?admissionTicketForm',
                            function () {
                                var data = ecui.esr.getData('data');
                                if (data instanceof Object) {
                                    this.findControl(ecui.ui.Dialog).hide();
                                    refreshCheckTicket();
                                    ecui.tip('warn', '成功入场');
                                }
                            }
                        );
                    }
                }
            }
        ),
        // 手机号列表
        Mobile: ecui.inherits(
            ecui.ui.Control,
            function (el, options) {
                ecui.ui.Control.call(this, el, options);
                this._sIndex = +options.index;
            },
            {
                onclick: function () {
                    var data = ticketItems[this._sIndex],
                        tab = this.findControl(ecui.ui.Tab),
                        ticketContainer = tab.getItem(1).getContainer(),
                        acount = ecui.esr.getData('acount');

                    if (data.total < 1) {
                        ecui.tip('warn', '该手机号未没有相关票务信息');
                        return;
                    }
                    ticketItem = data;
                    ecui.dispose(ticketContainer);
                    ticketContainer.innerHTML = ecui.esr.getEngine().render('ticketItems', { 'ticketItem': data, 'entryAmount': acount.entryAmount, 'lastAmount': acount.lastAmount });
                    ecui.init(ticketContainer);
                    tab.setSelected(1);
                }
            }
        ),
        // 票数输入框
        Number: ecui.inherits(
            ecui.ui.Control,
            'ui-ticket-number',
            function (el, options) {
                ecui.ui.Control.call(this, el, options);
                this._sMax = +this.max || +options.value;

                var children = dom.children(el);
                this._uPrev = ecui.$fastCreate(this.Prev, children[0], this, options);
                this._uNumber = ecui.$fastCreate(this.Number, children[1], this, options);
                this._uNext = ecui.$fastCreate(this.Next, children[2], this, options);
            },
            {
                Number: ecui.inherits(
                    ecui.ui.Number,
                    {
                        oninput: function () {
                            var value = +this.getValue(),
                                parent = this.getParent();
                            if (value > parent._sMax) {
                                this.$setValue(parent._sMax);
                            } else if (value < 0) {
                                this.$setValue(0);
                            }
                        },
                        onfocus: function (event) {
                            var panel = ecui.get('check-ticket-panel');
                            this._pY = panel.getY();
                            this._sLeft = panel.getMain().scrollLeft;
                            this._sTop = panel.getMain().scrollTop;
                            console.log(panel.getScrollRange().top);
                            util.timer(function () {
                                util.timer(function () {
                                    panel.getScrollRange({top: 0, bottom: -panel.getScrollRange().top});
                                }, 0);
                                // console.log(panel.getScrollRange());
                                // panel.setPosition(0, this._pY);
                                panel.getBody().style.transform = 'translate(0px, 0px)';
                                // panel.getMain().scrollTo(this._sLeft, this._sTop);
                            }.bind(this), 600);
                        },
                        prev: function () {
                            this.setValue(+this.getValue() - 1);
                        },
                        next: function () {
                            this.setValue(+this.getValue() + 1);
                        },
                        setValue: function (value) {
                            var parent = this.getParent();
                            value = +value;
                            if (value > parent._sMax) {
                                value = parent._sMax;
                            } else if (value < 0) {
                                value = 0;
                            }
                            this.$setValue(value);
                        }
                    }
                ),
                Prev: ecui.inherits(
                    ecui.ui.Button,
                    {
                        onclick: function () {
                            this.getParent()._uNumber.prev();
                        }
                    }
                ),
                Next: ecui.inherits(
                    ecui.ui.Button,
                    {
                        onclick: function () {
                            this.getParent()._uNumber.next();
                        }
                    }
                ),
                onclick: function (event) {
                    event.exit();
                }
            }
        )
    });
    ecui.esr.addRoute('check', {
        model: [
            'acount@GET /erp-management/play/h5/start-check-ticket/${id}'
        ],
        weight: 3,
        main: 'ticket_check',
        view: 'check',
        frame: true,
        onbeforerequest: function (context) {
            playId = context.id;
        },
        onbeforerender: function (context) {

            context.iosVersion = /(iPhone|iPad).*?OS (\d+(_\d+)?)/i.test(navigator.userAgent) ?  +(RegExp.$2.replace('_', '.')) : undefined;
        },
        onafterrender: function (context) {
        },
        onleave: function () {
            var dialog = ecui.get('check-ticket-dialog');
            if (dialog) {
                dialog.hide();
            }
        }
    });
}());